<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/murmur/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/murmur/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/murmur/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/murmur/images/logo.svg" color="#222">

<link rel="stylesheet" href="/murmur/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.css">
  <script src="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.js"></script>

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/murmur/","scheme":"Gemini","version":"8.0.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"disqus","storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}};
  </script>

  <meta name="description" content="第2章：词法作用域 第一章提到，所谓作用域就是JavaScript变量的存取规则。 而众多编程语言的作用域规则中，一般有两套工作模式：词法作用域和动态作用域。 JavaScript作用域采用的是词法作用域 ，以下主要讲解这种工作模式。  2.1 词法阶段 本书第一章说，在编译时期会进行词法分析，即将文本内容分解成有意义的词法字符串。比如var a &#x3D; 2;最终会分解成[var、a、&#x3D;、2、;] 所">
<meta property="og:type" content="article">
<meta property="og:title" content="《你不知道的JavaScript(上)》S01E02">
<meta property="og:url" content="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E02/index.html">
<meta property="og:site_name" content="汇话板">
<meta property="og:description" content="第2章：词法作用域 第一章提到，所谓作用域就是JavaScript变量的存取规则。 而众多编程语言的作用域规则中，一般有两套工作模式：词法作用域和动态作用域。 JavaScript作用域采用的是词法作用域 ，以下主要讲解这种工作模式。  2.1 词法阶段 本书第一章说，在编译时期会进行词法分析，即将文本内容分解成有意义的词法字符串。比如var a &#x3D; 2;最终会分解成[var、a、&#x3D;、2、;] 所">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-11-29T14:13:03.000Z">
<meta property="article:modified_time" content="2020-12-01T15:07:29.642Z">
<meta property="article:author" content="William Leung">
<meta property="article:tag" content="你不知道的JavaScript">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E02/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>《你不知道的JavaScript(上)》S01E02 | 汇话板</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?a49081c570a782a242cdf6e19e1a584d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/murmur/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">汇话板</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">设定目标，放慢步调，用温和的力量自我改革</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/murmur/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/murmur/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <section class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%AC%AC2%E7%AB%A0%EF%BC%9A%E8%AF%8D%E6%B3%95%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="nav-number">1.</span> <span class="nav-text">第2章：词法作用域</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1-%E8%AF%8D%E6%B3%95%E9%98%B6%E6%AE%B5"><span class="nav-number">1.1.</span> <span class="nav-text">2.1 词法阶段</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2-%E6%AC%BA%E9%AA%97%E8%AF%8D%E6%B3%95"><span class="nav-number">1.2.</span> <span class="nav-text">2.2 欺骗词法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#eval-%E5%87%BD%E6%95%B0"><span class="nav-number">1.2.0.1.</span> <span class="nav-text">eval()函数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#with-%E5%87%BD%E6%95%B0"><span class="nav-number">1.2.0.2.</span> <span class="nav-text">with()函数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%80%A7%E8%83%BD"><span class="nav-number">1.2.0.3.</span> <span class="nav-text">性能</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-3-%E5%B0%8F%E7%BB%93"><span class="nav-number">1.3.</span> <span class="nav-text">2.3 小结</span></a></li></ol></li></ol></div>
        </section>
        <!--/noindex-->

        <section class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">William Leung</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/murmur/archives">
          <span class="site-state-item-count">43</span>
          <span class="site-state-item-name">文章</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/murmur/categories/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/murmur/tags/">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </section>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">
      

      

  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E02/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/murmur/images/avatar.gif">
      <meta itemprop="name" content="William Leung">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="汇话板">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          《你不知道的JavaScript(上)》S01E02
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2020-11-29 22:13:03" itemprop="dateCreated datePublished" datetime="2020-11-29T22:13:03+08:00">2020-11-29</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2020-12-01 23:07:29" itemprop="dateModified" datetime="2020-12-01T23:07:29+08:00">2020-12-01</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/murmur/categories/%E4%B8%80%E5%91%A8%E4%B8%80%E7%AB%A0%E5%89%8D%E7%AB%AF%E4%B9%A6/" itemprop="url" rel="index"><span itemprop="name">一周一章前端书</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>2.4k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>2 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="第2章：词法作用域"><a href="#第2章：词法作用域" class="headerlink" title="第2章：词法作用域"></a>第2章：词法作用域</h1><ul>
<li>第一章提到，所谓作用域就是JavaScript变量的存取规则。</li>
<li>而众多编程语言的作用域规则中，一般有两套工作模式：<code>词法作用域</code>和<code>动态作用域</code>。</li>
<li><strong>JavaScript作用域采用的是<code>词法作用域</code></strong> ，以下主要讲解这种工作模式。</li>
</ul>
<h2 id="2-1-词法阶段"><a href="#2-1-词法阶段" class="headerlink" title="2.1 词法阶段"></a>2.1 词法阶段</h2><ul>
<li>本书第一章说，在编译时期会进行词法分析，即将文本内容分解成有意义的词法字符串。比如<code>var a = 2;</code>最终会分解成[<code>var</code>、<code>a</code>、<code>=</code>、<code>2</code>、<code>;</code>]</li>
<li>所谓 <strong><code>词法作用域</code>，就是在词法分析阶段就确定了变量处于哪个作用域，从而确定了变量可访问的范围。</strong><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> b = a * <span class="number">2</span>;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">bar</span>(<span class="params">c</span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(a, b, c);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">foo(<span class="number">2</span>);  <span class="comment">//2, 4, 12</span></span><br></pre></td></tr></table></figure></li>
<li>分析如上代码：<ul>
<li>总共有3个作用域<ol>
<li><strong>全局作用域</strong> ，定义了<code>foo</code>函数；</li>
<li><strong><code>foo</code>函数作用域</strong> ，定义了形参<code>a</code>、函数<code>bar</code>和变量<code>b</code>；</li>
<li><strong><code>bar</code>函数作用域</strong> ，只定义了形参<code>c</code>；</li>
</ol>
</li>
<li>由此可见，<strong>变量的作用域，就相当于所在函数的花括号包含的范围（除了全局作用域），并且作用域之间是逐级嵌套的。</strong></li>
<li><strong>变量的查找是由内往外的。</strong> JS引擎执行代码<code>console.log(a, b, c)</code>;时：<ol>
<li>首先是从<code>bar</code>函数作用域中查找<code>a</code>，<code>b</code>，<code>c</code>三个变量，只找到变量<code>c</code>；</li>
<li>接着到上一级的<code>foo</code>函数作用域，查到了变量<code>a</code>和<code>b</code>；</li>
</ol>
</li>
<li><strong>在多个作用域层嵌套的情况下，当子级作用域包含有父级作用域同名的变量时，则忽略父级变量，直接使用子级的变量，这称为“<code>遮蔽效应</code>”。</strong></li>
</ul>
</li>
</ul>
<h2 id="2-2-欺骗词法"><a href="#2-2-欺骗词法" class="headerlink" title="2.2 欺骗词法"></a>2.2 欺骗词法</h2><ul>
<li>既然变量的作用域就是函数的范围，且在词法分析阶段已经确定了，能否为某个变量动态植入到指定作用域里呢，达到类似<code>欺骗式的词法作用域</code>的效果？当然是可以的！</li>
<li><strong>JavaScript有两种机制实现所谓的<code>欺骗词法</code>：<code>eval</code>和<code>with</code>。</strong> 虽然滥用欺骗词法有可能会带来性能问题，不推荐使用。但不妨碍我们通过它，从而进一步的深入了解JavaScript作用域。<h4 id="eval-函数"><a href="#eval-函数" class="headerlink" title="eval()函数"></a><code>eval()</code>函数</h4></li>
<li><strong><code>eval()</code>函数接收一个代码字符串作为参数，通知JS引擎来执行它。</strong> 字符串代码中的作用域，动态的以eval()函数执行所在的作用域为准。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">str, a</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">eval</span>(str);</span><br><span class="line">    <span class="built_in">console</span>.log(a, b);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> b = <span class="number">2</span>;</span><br><span class="line">foo(<span class="string">&quot;var b = 3;&quot;</span>, <span class="number">1</span>);  <span class="comment">//输出 1, 3</span></span><br></pre></td></tr></table></figure></li>
<li>由于<code>eval()</code>在<code>foo</code>函数作用域中执行，所以<code>str</code>代码字符串中的变量<code>b</code>动态植入到<code>foo</code>函数作用域，从而执行<code>console.log()</code>输出时，屏蔽了全局作用域中同名的变量<code>b</code></li>
<li>由此可见，<code>eval()</code>函数可以在运行期修改词法分析阶段确定的作用域。值得一提的是，除了<code>eval()</code>函数之外，JavaScript很多原生的函数也具有欺骗词法的作用，比如<code>setTmeout()</code>、<code>setInterval()</code>等。</li>
</ul>
<h4 id="with-函数"><a href="#with-函数" class="headerlink" title="with()函数"></a><code>with()</code>函数</h4><ul>
<li><strong><code>with()</code>函数</strong> 可以交换词法作用域，<strong>通常可以当作重复引用同一个对象中的多个属性的快捷方式。</strong><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a : <span class="number">1</span>,</span><br><span class="line">    b : <span class="number">2</span>,</span><br><span class="line">    c : <span class="number">3</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//正常的调用需要重复的引用Obj对象</span></span><br><span class="line">obj.a = <span class="number">10</span>;</span><br><span class="line">obj.b = <span class="number">20</span>;</span><br><span class="line">obj.c = <span class="number">30</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//单通过with可以构造一个，obj对象引用的快捷方式</span></span><br><span class="line"><span class="function"><span class="title">with</span>(<span class="params">obj</span>)</span>&#123;</span><br><span class="line">    <span class="comment">//with代码内this默认指向obj对象</span></span><br><span class="line">    a = <span class="number">10</span>;</span><br><span class="line">    b = <span class="number">20</span>;</span><br><span class="line">    c = <span class="number">30</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>前面我们一直说，欺骗词法会引发性能问题，我们针对<code>with()</code>函数举个例子，看看如何造成全局变量污染的：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//定义一个foo方法</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">obj</span>)</span>&#123;</span><br><span class="line">    <span class="comment">//方法体中，通过with快捷方式对传入的对象进行赋值操作</span></span><br><span class="line">    <span class="function"><span class="title">with</span>(<span class="params">obj</span>)</span>&#123;</span><br><span class="line">        a = <span class="number">2</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//定义对象obj1，包含a属性</span></span><br><span class="line"><span class="keyword">var</span> obj1 = &#123;</span><br><span class="line">    a : <span class="number">3</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//定义对象obj2，不包含a属性</span></span><br><span class="line"><span class="keyword">var</span> obj2 = &#123;</span><br><span class="line">    b : <span class="number">3</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//调用foo函数，并传入obj1对象作为参数</span></span><br><span class="line">foo(obj1);</span><br><span class="line"><span class="built_in">console</span>.log(obj1.a);    <span class="comment">//输出 2，foo()方法将a属性成功改为2</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//调用foo函数，并传入obj2对象作为参数</span></span><br><span class="line">foo(obj2);</span><br><span class="line"><span class="built_in">console</span>.log(obj2.a);    <span class="comment">//输出 undefined，由于obj2对象没有a属性，所以赋值失败</span></span><br><span class="line"><span class="built_in">console</span>.log(a); <span class="comment">//输出2，属性a的赋值，暴露到了全局作用域上了</span></span><br></pre></td></tr></table></figure></li>
<li>如以上代码所示，<code>with()</code>函数有可能将赋值的属性转移给全局作用域，这也正是<code>with</code>与<code>eval</code>的区别：<ul>
<li><code>eval()</code>可以动态修改词法作用域；</li>
<li><code>with()</code>是根据传递的对象，凭空创建一个全新的词法作用域；所以当<code>obj2</code>作为参数进行<code>with</code>赋值操作的时候，由于<code>a</code>属性不存在，所以执行正常的LHS查询。</li>
</ul>
</li>
</ul>
<h4 id="性能"><a href="#性能" class="headerlink" title="性能"></a>性能</h4><ul>
<li><code>eval</code>和<code>with</code>会导致全局作用域的变量污染，这只是造成性能问题的一个方面。</li>
<li>除此之外，JavaScript引擎在编译阶段，会对代码进行性能优化，此类工作依赖于代码是静态的词法作用域。因为这是确定了作用域位置的变量，而如果是<code>eval</code>和<code>with</code>的方式，引擎则直接忽略，完全不做任何优化。</li>
<li>并且如果项目中大量使用<code>eval</code>和<code>with</code>进行动态作用域指定，最后参与编码的开发者也会懵逼。 <strong>我们应该秉承JS引擎的规则，将变量限制在最小范围内。</strong></li>
</ul>
<h2 id="2-3-小结"><a href="#2-3-小结" class="headerlink" title="2.3 小结"></a>2.3 小结</h2><ul>
<li><strong>JavaScript有两种机制欺骗词法：<code>eval</code>和<code>with</code>：<code>eval</code>可以动态调用JS引擎执行传入的代码字符串，由此来修改词法作用域；<code>with</code>可以将一个对象的引用，创建一个新的作用域来处理。</strong></li>
<li><strong>由于这两种机制，JS引擎无法在编译阶段对作用域查找进行优化，所以警惕滥用此类函数，从而造成性能问题。</strong></li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>William Leung
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E02/" title="《你不知道的JavaScript(上)》S01E02">https://gitee.com/lianghuilin/murmur.git/reading_notes/《你不知道的JavaScript-上-》S01E02/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/murmur/tags/%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript/" rel="tag"># 你不知道的JavaScript</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/murmur/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E01/" rel="prev" title="《你不知道的JavaScript(上)》S01E01">
                  <i class="fa fa-chevron-left"></i> 《你不知道的JavaScript(上)》S01E01
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/murmur/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E03/" rel="next" title="《你不知道的JavaScript(上)》S01E03">
                  《你不知道的JavaScript(上)》S01E03 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






      

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">
      

      

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">William Leung</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
    <span title="站点总字数">142k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">2:09</span>
  </span>
</div>
<div class="busuanzi-count">
    <span id="busuanzi_container_site_uv">
      本站访客数<span id="busuanzi_value_site_uv"></span>人次
    </span>
    <span id="busuanzi_container_site_pv">
        本站总访问量<span id="busuanzi_value_site_pv"></span>次
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/murmur/js/utils.js"></script><script src="/murmur/js/motion.js"></script><script src="/murmur/js/next-boot.js"></script>

  
















  <script>
    NProgress.configure({
      showSpinner: true
    });
    NProgress.start();
    document.addEventListener('readystatechange', () => {
      if (document.readyState === 'interactive') {
        NProgress.inc(0.8);
      }
      if (document.readyState === 'complete') {
        NProgress.done();
      }
    });
    document.addEventListener('pjax:send', () => {
      NProgress.start();
    });
    document.addEventListener('pjax:success', () => {
      NProgress.done();
    });
  </script>


  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>








  

  

</body>
</html>
